using System.Collections.Generic;
using System;

namespace Super
{
    public class CountDictionary<T>
    {
        private Dictionary<T, int> countDict = new Dictionary<T, int>();

        public CountDictionary()
        {
            countDict.Clear();
        }

        public CountDictionary(List<T> values)
        {
            countDict.Clear();

            if (values == null)
            {
                throw new ArgumentNullException(nameof(values), "Input list cannot be null.");
            }

            foreach (var item in values)
            {
                if (countDict.ContainsKey(item))
                {
                    countDict[item]++;
                }
                else
                {
                    countDict[item] = 1;
                }
            }
        }

        /// <summary>
        /// 增加指定项的计数
        /// </summary>
        /// <param name="item">要增加计数的项</param>
        /// <param name="count">增加的数量（默认为1）</param>
        public void Add(T item, int count = 1)
        {
            if (count <= 0)
            {
                throw new ArgumentException("Count must be positive.", nameof(count));
            }

            if (countDict.ContainsKey(item))
            {
                countDict[item] += count;
            }
            else
            {
                countDict[item] = count;
            }
        }

        /// <summary>
        /// 减少指定项的计数，如果计数降至零则移除该项
        /// </summary>
        /// <param name="item">要减少计数的项</param>
        /// <param name="count">减少的数量（默认为1）</param>
        /// <returns>操作后的计数，如果项不存在或已被移除则返回0</returns>
        public int Remove(T item, int count = 1)
        {
            if (count <= 0)
            {
                throw new ArgumentException("Count must be positive.", nameof(count));
            }

            if (countDict.TryGetValue(item, out int currentCount))
            {
                if (currentCount > count)
                {
                    countDict[item] = currentCount - count;
                    return currentCount - count;
                }
                else
                {
                    countDict.Remove(item);
                    return 0;
                }
            }
            return 0;
        }

        /// <summary>
        /// 获取指定项的当前计数
        /// </summary>
        public int GetCount(T item)
        {
            return countDict.TryGetValue(item, out int count) ? count : 0;
        }

        /// <summary>
        /// 检查字典中是否包含指定项（计数大于零）
        /// </summary>
        public bool Contains(T item)
        {
            return countDict.ContainsKey(item);
        }

        /// <summary>
        /// 清空字典
        /// </summary>
        public void Clear()
        {
            countDict.Clear();
        }
    }
}